package cn.zhoujing.demo.redis.config;

import cn.zhoujing.demo.redis.service.impl.CustomUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author zhoujing
 * @createTime 2023/11/19 - 14:20
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsServiceImpl customUserDetailsServiceImpl;

    /**
     * {@link AuthorizationServerConfig} 认证服务中需要使用，提前放入IOC容器中
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 安全拦截机制
     *
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // CSRF禁用，因为不使用session
                .csrf().disable()
                .authorizeRequests()
                // 登录和静态资源不需要认证
                .antMatchers("/login/**", "/css/**", "/auth/**","/oauth/**").permitAll()
                // 除上面的所有请求全部需要认证通过才能访问
                .anyRequest().authenticated()
                // 返回HttpSecurity以进行进一步的自定义,证明是一次新的配置的开始
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .permitAll();
    }

    /**
     * 身份验证管理器生成器，用于认证用户信息
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsServiceImpl);
    }


}
